package com.dq.edusms.controller;

import com.dq.commonutils.vo.Result;
import com.dq.edusms.service.SmsService;
import com.dq.edusms.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @project: guli_parent
 * @ClassName: SmsController
 * @author: dq
 * @creat: 2022/8/7 15:33
 */
@RestController
@RequestMapping("edusms/sms")
// @CrossOrigin
public class SmsController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 短信发送
     *
     * @param phoneNum
     * @return
     */
    @GetMapping("sendMessage/{phone}")
    public Result sendMessage(@PathVariable("phone") String phoneNum) {
        /**
         * 1.获取redis消息（发送信息是否成功）
         * 2. 如果没有这条消息则进行消息发送
         * 3. 有的话直接返回true
         */
        String data = redisTemplate.opsForValue().get(phoneNum);
        if (!StringUtils.isEmpty(data)) {
            return Result.success(null);
        }
        HashMap<String, Object> param = new HashMap<>();
        String code = RandomUtil.getFourBitRandom();
        param.put("code", code);
        boolean isSend = smsService.send(param, phoneNum);

        if (isSend) {
            redisTemplate.opsForValue().set(phoneNum, code, 5, TimeUnit.MINUTES);
            return Result.success(null);
        } else {
            return Result.error(20001, "短信发送失败");
        }
    }
}
